package com.overlook.somniferous.user.advice;


import com.overlook.somniferous.common.Enum.CommonErrorEnum;
import com.overlook.somniferous.common.exception.BusinessException;
import com.overlook.somniferous.common.po.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    /**
     * 自定义异常
     *
     * @param e 自定义异常
     * @return
     */
    @ExceptionHandler({BusinessException.class})
    public Result handleException(BusinessException e) {
        log.error("BusinessException error message{}", e.getMessage());
        return Result.error(e.getCode(), e.getMessage(), null);
    }

    /**
     * 参数校验异常
     *
     * @param e 参数校验异常
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result handleValidException(MethodArgumentNotValidException e) {
        StringBuffer sb = new StringBuffer();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            sb.append(defaultMessage);
            sb.append(System.getProperty("line.separator"));
        }
        log.error("MethodArgumentNotValidException error message:{}", sb);
        return Result.error(CommonErrorEnum.PARAM_ERROR.getCode(), sb.toString());
    }
}
